package com.bytesizedhosting.api.android.darthcrap.screens.maintabs;

import org.eclipse.mylyn.wikitext.core.parser.MarkupParser;
import org.eclipse.mylyn.wikitext.textile.core.TextileLanguage;

import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bytesizedhosting.api.android.darthcrap.ExtendedActivity;
import com.bytesizedhosting.api.android.darthcrap.NullArgumentException;
import com.bytesizedhosting.api.android.darthcrap.R;
import com.bytesizedhosting.api.android.darthcrap.api.APIController;
import com.bytesizedhosting.api.android.darthcrap.api.APIData.NewsItem;
import com.bytesizedhosting.api.android.darthcrap.components.accordian.Accordian;
import com.bytesizedhosting.api.android.darthcrap.components.accordian.AccordianEntry;

public class NewsTab extends ExtendedActivity {
	private static Accordian.StateContainer objStateContainer = new Accordian.StateContainer();
	private Accordian objAccordian = null;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newstab);
        
        this.objAccordian = (Accordian)findViewById(R.id.accMain);
        this.objAccordian.setStateContainer(objStateContainer);
        
        for (NewsItem objNewsItem : APIController.getData().getNewsItemIterator()) {
        	objAccordian.addEntry(new NewsItemEntry(objNewsItem));
        }
        
        this.objAccordian.restoreState();
    }
    
    public void onConfigurationChanged(Configuration objNewConfig) {
    	this.objAccordian.holdState();
    	super.onConfigurationChanged(objNewConfig);
    }
    
    private static class NewsItemEntry extends AccordianEntry {
    	private NewsItem objNewsItem = null;
    	private static MarkupParser objParser = new MarkupParser(new TextileLanguage());
    	
    	public NewsItemEntry(NewsItem objNewsItem) {
    		super(objNewsItem.getTitle());
    		NullArgumentException.testArguments(objNewsItem);
    		this.objNewsItem = objNewsItem;
    	}
    	
		@Override
		protected void buildEntryView(LayoutInflater objInflater, LinearLayout objRootLayout) {
			TextView objTextView = (TextView)objInflater.inflate(R.layout.newsitem,objRootLayout,false);
			objTextView.setMovementMethod(LinkMovementMethod.getInstance());
			objTextView.setText(Html.fromHtml(objParser.parseToHtml(this.objNewsItem.getBody())));
			objRootLayout.addView(objTextView);
		}

		@Override
		public int hashCode() {
			return this.objNewsItem.hashCode();
		}
    }
}